﻿using System;
using System.Windows.Forms;
using SdmxMl.Common;
using System.Configuration;

namespace SdmxMl.Panels
{
    /// <summary> Dialog for Edition of an SDMX Annotation.</summary>
    public partial class DlgEditAnnotation : Form
    {
        #region Internal Members

        private Annotation annotation;

        #endregion

        #region Properties

        private bool _isFinal;
        public bool IsFinal
        {
            set
            {
                _isFinal = value;
                IsFinalEditControls(_isFinal);
            }
        }

        // No edition if Parent Artefact IsFinal
        private void IsFinalEditControls(bool isFinal)
        {
            bool enabled = isFinal == false;

            comboBoxType.Enabled = enabled;
            comboMultiLines.IsFinal = isFinal;
            textBoxTitle.ReadOnly = isFinal;
            textBoxUrl.ReadOnly = isFinal;
            textBoxId.ReadOnly = isFinal;
        }

        public Annotation Ann
        {
            get { return annotation; }
            set 
            { 
                annotation = value;
                this.comboMultiLines.ML = annotation.Text;
                this.textBoxTitle.Text = annotation.Title;
                this.comboBoxType.Text = annotation.Type;
                this.textBoxId.Text = annotation.Id;
                this.textBoxUrl.Text = annotation.Url == null ? string.Empty : annotation.Url.ToString();
            }
        }

        #endregion

        #region C'tor
        public DlgEditAnnotation()
        {
            InitializeComponent();

            string configTag = "SuggestedAnnotationType";
            // if configuration with annotation types suggestions, fill combo with it (SuggestedAnnotationType)
            if (ConfigurationManager.AppSettings[configTag] != null)
            {
                string[] arr = ConfigurationManager.AppSettings[configTag].Trim().Split(',');
                comboBoxType.Items.Clear();
                foreach (string s in arr)
                    comboBoxType.Items.Add(s.Trim());
            }

        }
        #endregion

        #region Button Events

        private void buttonOk_Click(object sender, EventArgs e)
        {
            try
            {
                annotation.Title = this.textBoxTitle.Text;
                annotation.Type = this.comboBoxType.Text;
                annotation.Id = textBoxId.Text;
                string uri = textBoxUrl.Text.Trim();
                annotation.Url = uri.Length > 0 ? new Uri(uri) : null;
                DialogResult = DialogResult.OK;
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error");
            }
        }
        #endregion
    }
}
